import API from '../../utils/api.js'
Page({
  data: {
    turnBack: 'back',
    cammerHeight: 300,
    isShowCammer: true,
    upPicList: [],
    file: "",
  }, 
  onLoad() {
    this.ctx = wx.createCameraContext()
  },
  upPic() {
    var _this = this
    wx.chooseImage({
      success(res) {
        const tempFilePaths = res.tempFilePaths
        console.log(tempFilePaths)
        _this.setData({
          tempFilePaths: tempFilePaths
        })
        for (var k in tempFilePaths) {
          _this.uploadFile(tempFilePaths[k])
        }
      }
    })
  },
  uploadFile(img) {
    console.log(img)
    var _this = this
    wx.showLoading({ title: '图片上传中...' })
    wx.uploadFile({
      url: 'https://www.szhongtu.net/mcbase/public/index.php/wxroutine/quanzi/upload',
      filePath: img,
      name: 'file',
      formData: {
        'user': 'test'
      },
      success(res) {
        wx.hideLoading()
        var data = JSON.parse(res.data)
        if (data.ret == 0) {
          _this.recognition(data.url)
        }
      }
    })
  },
  //镜头转换
  retunCammerHead() {
    console.log("镜头转换");
    var status = this.data.turnBack
    var state = ''
    if (status == 'back') {
      state = 'front'
    } else {
      state = 'back'
    }
    this.setData({
      turnBack: state
    })
  },
  //照相
  takePhoto() {
    var _this = this
    this.ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        wx.showLoading({
          title: '识别中...',
        })
        console.log(res)
        _this.uploadFile(res.tempImagePath)

      }
    })
  },
  // 图像识别
  recognition(img) {
    var data = {
      imageurl: img,
    }
    API.recognition(data).then(res => {
      if (res.ret == 0) {
        console.log(res);
        // wx.showModal({
        //   title: '识别成功',
        //   content: res.data.result[0].name
        // })
        wx.setStorageSync('name', res.data.result[0].name);
        wx.setStorageSync('image_url', res.data.result[0].baike_info.image_url);
        wx.setStorageSync('description', res.data.result[0].baike_info.description);
        wx.navigateTo({
          url: '/pages/scan/scan'
        })
      }else{
         wx.showModal({
          title: '识别成功',
          content: res.data.result[0].name
        })
      }
    })
  }
})